using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using SJVars;
using SJXmlP.XMLClasses;
using Spacejock;
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using yW5Lib;
using yWriter6.My.Resources;

namespace yWriter6
{
	public class clsExportToEbook
	{
		public delegate void ProgressEventHandler(string ProgressString, long Count, long Total);

		private clsRTF RTFToText;

		private clsPreserveHTM cPreserve;

		private bool RunCalibre;

		private string ExporterName;

		private clsSettings cExporter;

		private clsProject cProject;

		[CompilerGenerated]
		private ProgressEventHandler ProgressEvent;

		private string strPageBreak;

		public event ProgressEventHandler Progress
		{
			[CompilerGenerated]
			add
			{
				ProgressEventHandler progressEventHandler = ProgressEvent;
				ProgressEventHandler progressEventHandler2;
				do
				{
					progressEventHandler2 = progressEventHandler;
					ProgressEventHandler value2 = (ProgressEventHandler)Delegate.Combine(progressEventHandler2, value);
					progressEventHandler = Interlocked.CompareExchange(ref ProgressEvent, value2, progressEventHandler2);
				}
				while ((object)progressEventHandler != progressEventHandler2);
			}
			[CompilerGenerated]
			remove
			{
				ProgressEventHandler progressEventHandler = ProgressEvent;
				ProgressEventHandler progressEventHandler2;
				do
				{
					progressEventHandler2 = progressEventHandler;
					ProgressEventHandler value2 = (ProgressEventHandler)Delegate.Remove(progressEventHandler2, value);
					progressEventHandler = Interlocked.CompareExchange(ref ProgressEvent, value2, progressEventHandler2);
				}
				while ((object)progressEventHandler != progressEventHandler2);
			}
		}

		public clsExportToEbook()
		{
			RTFToText = new clsRTF(ref clsShared.cLog, ref clsShared.cSettings);
			cPreserve = new clsPreserveHTM();
			RunCalibre = false;
			ExporterName = "";
			strPageBreak = "<h2 class='pagebreak'> &nbsp; </h2>";
		}

		public void ExportToEbook(clsProject ProjectClass, bool AskForOutputFile, bool AskWhichChapters, bool ToSingleFiles)
		{
			cProject = ProjectClass;
			if (cProject.ChapterCount == 0)
			{
				return;
			}
			string text = "";
			clsCollection<int> clsCollection = new clsCollection<int>();
			if (!AskWhichChapters)
			{
				clsCollection = cProject.AllChapterIDs();
				text = Path.Combine(cProject.ExportFolder(), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".html");
				if (AskForOutputFile)
				{
					text = clsShared.cFileSel.GetOutputFilename("Enter a filename", Path.Combine(cProject.ProjectPath(), "Export"), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".html", "*.HTML", !clsShared.cSettings.sGet("OverwriteExport", DefaultIfUnknown: false));
				}
				if (text.Length > 0 && DoExport(text, ToSingleFiles, ref clsCollection, AskForOutputFile))
				{
					clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
					clsShared.cFile.RunFile(text);
				}
				return;
			}
			frmPickChapters frmPickChapters = new frmPickChapters(ref cProject);
			frmPickChapters.HidePrinterSelect();
			frmPickChapters.HideTagFilter();
			frmPickChapters.HideVPFilter();
			frmPickChapters.EnableAllPresets();
			frmPickChapters.EnableMobiEpubSelect();
			frmPickChapters.ShowDialog();
			if (frmPickChapters.Cancelled)
			{
				return;
			}
			if (frmPickChapters.optAllPresets.Checked)
			{
				IEnumerator enumerator = default(IEnumerator);
				try
				{
					enumerator = cProject.cExports.GetEnumerator();
					while (enumerator.MoveNext())
					{
						clsExport clsExport = (clsExport)enumerator.Current;
						text = clsExport.Filename;
						if (Operators.CompareString(clsExport.ImageFile, "", TextCompare: false) != 0)
						{
							RunCalibre = true;
							ExporterName = clsExport.ImageFile;
						}
						else
						{
							RunCalibre = false;
						}
						text = ((Operators.CompareString(text, "", TextCompare: false) != 0) ? Path.Combine(cProject.ExportFolder(), text + ".html") : Path.Combine(cProject.ExportFolder(), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".html"));
						clsCollection = cProject.SelectedChapterIDs(clsExport.ChIDsSemiColonSeparated, frmPickChapters.WithUnused);
						if (DoExport(text, ToSingleFiles, ref clsCollection, AskForOutputFile) && RunCalibre)
						{
							bool doMobi = false;
							bool doEpub = false;
							if (clsExport.Tags.Contains("mobi"))
							{
								doMobi = true;
							}
							if (clsExport.Tags.Contains("epub"))
							{
								doEpub = true;
							}
							ConvertToEpub(text, ExporterName, doMobi, doEpub);
						}
					}
				}
				finally
				{
					if (enumerator is IDisposable)
					{
						(enumerator as IDisposable).Dispose();
					}
				}
				if (text.Length > 0)
				{
					clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
				}
				return;
			}
			RunCalibre = frmPickChapters.RunCalibre;
			ExporterName = frmPickChapters.EbookProfileName;
			text = frmPickChapters.PickedFilename;
			text = ((Operators.CompareString(text, "", TextCompare: false) != 0) ? Path.Combine(cProject.ExportFolder(), text + ".html") : Path.Combine(cProject.ExportFolder(), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".html"));
			if (text.Length <= 0)
			{
				return;
			}
			clsCollection = frmPickChapters.PickedIDs;
			if (!DoExport(text, ToSingleFiles, ref clsCollection, AskForOutputFile))
			{
				return;
			}
			if (RunCalibre)
			{
				if (ConvertToEpub(text, ExporterName, frmPickChapters.chkExportMobiFormat.Checked, frmPickChapters.chkExportEpubFormat.Checked))
				{
					clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
				}
			}
			else
			{
				clsShared.cFile.RunFile(text);
				clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
			}
		}

		private bool DoExport(string Filename, bool ToSingleFiles, ref clsCollection<int> colIDs, bool AskForOutputFile)
		{
			try
			{
				RichTextBox richTextBox = new RichTextBox();
				clsShared.cSettings.sGet("EditorFontName", "Segoe UI");
				clsShared.cSettings.sGet("EditorFontSize", 10f);
				string text = "";
				string value = "<center>" + cProject.HtmlSceneDivider + "</center>";
				if (Operators.CompareString(Filename, "", TextCompare: false) == 0)
				{
					return false;
				}
				clsShared.cSubs.BusyMouse();
				string text2 = "";
				string text3 = "";
				StringBuilder stringBuilder = new StringBuilder();
				string text4 = "@@#$TITLE$#@@";
				text2 = Resources.HtmlHead + "\r\n";
				if (Operators.CompareString(cProject.HtmlEncoding, "", TextCompare: false) != 0)
				{
					text2 = Strings.Replace(text2, "utf-8", cProject.HtmlEncoding);
				}
				text2 = text2 + "<TITLE>" + text4 + "</TITLE>\r\n";
				text2 = text2 + Resources.CSSEbook + "\r\n";
				text2 += "</HEAD>\r\n";
				text2 += "<BODY>\r\n";
				text3 = "</BODY>\r\n";
				text3 += "</HTML>\r\n";
				if (!ToSingleFiles)
				{
					stringBuilder.AppendLine(Strings.Replace(text2, text4, clsShared.cHtml.TextToHtmlConst(cProject.Title) + " by " + clsShared.cHtml.TextToHtmlConst(cProject.AuthorName)));
				}
				else
				{
					value = "<br /><br />";
				}
				int num = colIDs.Count();
				int num2 = 0;
				IEnumerator enumerator = default(IEnumerator);
				try
				{
					enumerator = cProject.Chapters.GetEnumerator();
					while (enumerator.MoveNext())
					{
						clsChapter clsChapter = (clsChapter)enumerator.Current;
						if (colIDs.Contains(clsChapter.ID))
						{
							num2++;
							bool flag = false;
							ProgressEvent?.Invoke(clsChapter.Title, num2, num);
							bool flag2 = false;
							if (!clsChapter.Unused & (clsChapter.Type == ChapterTypes.ChapterNormal))
							{
								if (ToSingleFiles)
								{
									stringBuilder.AppendLine(Strings.Replace(text2, text4, clsShared.cHtml.TextToHtmlConst(clsChapter.Title) + " by " + clsShared.cHtml.TextToHtmlConst(cProject.AuthorName)));
								}
								string proposedFilename = Path.Combine(clsShared.cFile.PathOnly(Filename), Strings.Replace(clsChapter.Title, " ", "") + ".html");
								proposedFilename = clsShared.cFile.StripBadFileChar(proposedFilename);
								text = (clsChapter.Title.StartsWith("@#") ? "" : ((!clsChapter.Title.StartsWith("@")) ? ("<p class='chapter'>" + clsShared.cHtml.TextToHtmlConst(clsChapter.Title) + "</p>") : "<p class='chapter'>&nbsp;</p>"));
								int sceneCount = clsChapter.SceneCount;
								for (int i = 1; i <= sceneCount; i++)
								{
									clsScene clsScene = cProject.get_SceneByChID(clsChapter.ID, i);
									if (!clsScene.Unused)
									{
										try
										{
											richTextBox.Rtf = modSubs.RTFWithParsedVars(cProject, clsScene, modVariables.eFinalExportType.Ebook);
										}
										catch (Exception ex)
										{
											ProjectData.SetProjectError(ex);
											Exception ex2 = ex;
											richTextBox.Text = clsScene.TextRTF;
											ProjectData.ClearProjectError();
										}
										string rtf = richTextBox.Rtf;
										if (richTextBox.Text.ToLower().StartsWith("<tex>"))
										{
											flag2 = false;
										}
										else if (!PassesExportFilters(clsScene))
										{
											flag2 = false;
										}
										else
										{
											flag2 = true;
											string text5 = DoConversion(rtf);
											if (Operators.CompareString(text5, "", TextCompare: false) != 0)
											{
												if (!flag)
												{
													stringBuilder.AppendLine(text);
													flag = true;
												}
												text5 = Strings.Replace(text5, "[/h1]", "");
												stringBuilder.AppendLine(text5);
												if (flag2 && i < clsChapter.SceneCount)
												{
													clsScene clsScene2 = cProject.get_SceneByChID(clsChapter.ID, i + 1);
													if ((!clsScene2.Unused & PassesExportFilters(clsScene2)) && !clsScene2.AppendToPrevious)
													{
														stringBuilder.AppendLine("");
														stringBuilder.AppendLine(value);
														stringBuilder.AppendLine("");
													}
												}
											}
										}
									}
								}
								if (ToSingleFiles)
								{
									stringBuilder.AppendLine(text3);
									clsShared.cFile.WriteAsciiForced(proposedFilename, stringBuilder.ToString());
									stringBuilder.Length = 0;
								}
							}
						}
					}
				}
				finally
				{
					if (enumerator is IDisposable)
					{
						(enumerator as IDisposable).Dispose();
					}
				}
				if (!ToSingleFiles)
				{
					stringBuilder.AppendLine(text3);
					clsShared.cFile.WriteAsciiForced(Filename, stringBuilder.ToString());
				}
				clsShared.cSubs.NormalMouse();
				return true;
			}
			catch (Exception ex3)
			{
				ProjectData.SetProjectError(ex3);
				Exception ex4 = ex3;
				clsShared.cSubs.NormalMouse();
				clsShared.cLog.AddAction(ex4, MethodBase.GetCurrentMethod());
				bool result = false;
				ProjectData.ClearProjectError();
				return result;
			}
		}

		public string DoConversion(string strRTF)
		{
			string BodyText = "";
			try
			{
				if (strRTF.Length > 0)
				{
					cPreserve.PreserveHtml(ref strRTF);
					BodyText = RTFToText.RtfToHTML(strRTF, IgnoreDocFont: true);
					clsShared.cText.RemoveCRLFFromEnd(ref BodyText);
					cPreserve.RestoreHtml(ref BodyText);
					BodyText = Strings.Replace(BodyText, "[pb]", strPageBreak);
					try
					{
						BodyText = BodyText.Trim();
						return BodyText;
					}
					catch (Exception ex)
					{
						ProjectData.SetProjectError(ex);
						Exception ex2 = ex;
						BodyText = "";
						ProjectData.ClearProjectError();
						return BodyText;
					}
				}
				BodyText = "";
				return BodyText;
			}
			catch (Exception ex3)
			{
				ProjectData.SetProjectError(ex3);
				Exception ex4 = ex3;
				ProjectData.ClearProjectError();
				return BodyText;
			}
		}

		private bool PassesExportFilters(clsScene Scene)
		{
			bool result = false;
			if (!Scene.ExportCondSpecific)
			{
				result = true;
			}
			else if (Scene.ExportWhenHTML)
			{
				result = true;
			}
			return result;
		}

		private bool ConvertToEpub(string InputFile, string ExporterName, bool DoMobi, bool DoEpub)
		{
			try
			{
				if (!DoEpub && !DoMobi)
				{
					clsShared.cLog.AddAction("In ConvertToEpub, neither Mobi nor Epub were selected. Nothing to do.");
					return false;
				}
				clsRTF clsRTF = new clsRTF(ref clsShared.cLog, ref clsShared.cSettings);
				string settingsFile = clsEpub.CreateFilenameFromExportName(ExporterName);
				string text = clsShared.cFile.FileWithoutExt(InputFile) + "_mobi." + clsShared.cFile.ExtOnly(InputFile);
				string text2 = clsShared.cFile.FileWithoutExt(InputFile) + "_epub." + clsShared.cFile.ExtOnly(InputFile);
				cExporter = new clsSettings(ref clsShared.cLog);
				cExporter.LoadSettings(settingsFile);
				string text3 = Path.Combine(clsShared.cSettings.sGet("CalibrePath", ""), "ebook-convert.exe");
				if (!clsShared.cFile.FileExists(text3))
				{
					clsShared.cLog.AddAction(text3 + " not found. Please specify path to Calibre.");
					return false;
				}
				string TextString = "";
				string text4 = "";
				string text5 = "";
				clsShared.cFile.ReadUnicodeForced(InputFile, ref TextString);
				text4 = TextString;
				clsShared.cHtml.StripBetweenTags(ref text4, "[epub_", "]");
				text5 = TextString;
				clsShared.cHtml.StripBetweenTags(ref text5, "[mobi_", "]");
				Collection collection = new Collection();
				IEnumerator enumerator = default(IEnumerator);
				try
				{
					enumerator = modVariables.cVarsGlobal.GetEnumerator();
					while (enumerator.MoveNext())
					{
						clsVar item = (clsVar)enumerator.Current;
						collection.Add(item);
					}
				}
				finally
				{
					if (enumerator is IDisposable)
					{
						(enumerator as IDisposable).Dispose();
					}
				}
				IEnumerator enumerator2 = default(IEnumerator);
				try
				{
					enumerator2 = cProject.cVars.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						clsVar item2 = (clsVar)enumerator2.Current;
						collection.Add(item2);
					}
				}
				finally
				{
					if (enumerator2 is IDisposable)
					{
						(enumerator2 as IDisposable).Dispose();
					}
				}
				IEnumerator enumerator3 = default(IEnumerator);
				try
				{
					enumerator3 = collection.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						clsVar clsVar = (clsVar)enumerator3.Current;
						string find = "[" + clsVar.Title + "]";
						if (clsVar.Title.ToLower().StartsWith("mobi_"))
						{
							text4 = Strings.Replace(text4, find, clsRTF.RtfToTxt(clsVar.DescText), 1, -1, CompareMethod.Text);
						}
						if (clsVar.Title.ToLower().StartsWith("epub_"))
						{
							text5 = Strings.Replace(text5, find, clsRTF.RtfToTxt(clsVar.DescText), 1, -1, CompareMethod.Text);
						}
					}
				}
				finally
				{
					if (enumerator3 is IDisposable)
					{
						(enumerator3 as IDisposable).Dispose();
					}
				}
				IEnumerator enumerator4 = default(IEnumerator);
				try
				{
					enumerator4 = collection.GetEnumerator();
					while (enumerator4.MoveNext())
					{
						clsVar clsVar2 = (clsVar)enumerator4.Current;
						string find = "[" + clsVar2.Title + "]";
						text4 = Strings.Replace(text4, find, clsRTF.RtfToTxt(clsVar2.DescText), 1, -1, CompareMethod.Text);
						text5 = Strings.Replace(text5, find, clsRTF.RtfToTxt(clsVar2.DescText), 1, -1, CompareMethod.Text);
					}
				}
				finally
				{
					if (enumerator4 is IDisposable)
					{
						(enumerator4 as IDisposable).Dispose();
					}
				}
				clsShared.cFile.WriteUnicodeForced(text, text4);
				clsShared.cFile.WriteUnicodeForced(text2, text5);
				StringBuilder stringBuilder = new StringBuilder();
				string str = "";
				string str2 = "";
				text3 = clsShared.cText.AddDoubleQuotes(text3);
				if (DoMobi)
				{
					str = text3 + " ";
					str = str + clsShared.cText.AddDoubleQuotes(text) + " ";
					str += clsShared.cText.AddDoubleQuotes(clsShared.cFile.FileWithoutExt(InputFile) + ".mobi ");
				}
				if (DoEpub)
				{
					str2 = text3 + " ";
					str2 = str2 + clsShared.cText.AddDoubleQuotes(text2) + " ";
					str2 += clsShared.cText.AddDoubleQuotes(clsShared.cFile.FileWithoutExt(InputFile) + ".epub ");
				}
				stringBuilder.Append(" --title=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("Title", "The Book Title")));
				stringBuilder.Append(" --title-sort=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("TitleSort", "Book Title,The")));
				stringBuilder.Append(" --authors=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("Author", "First Last")));
				stringBuilder.Append(" --author-sort=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("AuthorSort", "Last,First")));
				stringBuilder.Append(" --publisher=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("Publisher", "")));
				stringBuilder.Append(" --comments=" + clsShared.cText.AddDoubleQuotes(Strings.Replace(cExporter.sGet("Blurb", ""), "\"", "\\\"")) + " ");
				stringBuilder.Append(" --pubdate=" + clsShared.cText.AddDoubleQuotes(Strings.Format(cExporter.sGet("PubDate", DateAndTime.Now.Date), "yyyy-MM-dd")) + " ");
				stringBuilder.Append("--cover=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("CoverFile", "")) + " ");
				stringBuilder.Append("--language=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("Language", "English")) + " ");
				stringBuilder.Append("--series=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("SeriesName", "")) + " ");
				stringBuilder.Append("--series-index=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("SeriesNumber", "")) + " ");
				stringBuilder.Append("--tags=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("Tags", "")) + " ");
				if (DoMobi)
				{
					StringBuilder stringBuilder2 = new StringBuilder();
					stringBuilder2.Append(stringBuilder.ToString());
					stringBuilder2.Append(" --isbn=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("MobiISBN", "")) + " ");
					stringBuilder2.Append(cExporter.sGet("MobiParam", clsEpub.strDefaultMobiParam) + " ");
					stringBuilder2.AppendLine();
					str += stringBuilder2.ToString();
					string filename = Path.Combine(modVariables.DATAPATH, "ConvertToMobi.bat");
					clsShared.cFile.WriteTextFile(filename, str);
					clsShared.cFile.RunFileWithWait(filename);
				}
				if (DoEpub)
				{
					StringBuilder stringBuilder3 = new StringBuilder();
					stringBuilder3.Append(stringBuilder.ToString());
					stringBuilder3.Append(" --isbn=" + clsShared.cText.AddDoubleQuotes(cExporter.sGet("EpubISBN", "")) + " ");
					stringBuilder3.Append(cExporter.sGet("EpubParam", clsEpub.strDefaultEpubParam) + " ");
					stringBuilder3.AppendLine();
					str2 += stringBuilder3.ToString();
					string filename = Path.Combine(modVariables.DATAPATH, "ConvertToEpub.bat");
					clsShared.cFile.WriteTextFile(filename, str2);
					clsShared.cFile.RunFileWithWait(filename);
				}
				return true;
			}
			catch (Exception ex)
			{
				ProjectData.SetProjectError(ex);
				Exception ex2 = ex;
				clsShared.cLog.AddAction(ex2, MethodBase.GetCurrentMethod());
				bool result = false;
				ProjectData.ClearProjectError();
				return result;
			}
		}
	}
}
